
;!function (win) {
  var upload = {};
  upload.options = {
    contentDomId: '#myUpload',
  }
  upload.init = function (options) {
    upload.options = options;
    if (upload.options) {
      //1、获取主容器对象
      var container = $(upload.options.contentDomId);
      container.addClass('upload');
      //2、创建上传附件的title（样式是否要参数化？）
      var uploadTitle = $('<span></span>').addClass('title')
                                          .html('上传附件：');
      container.append(uploadTitle);
      //3、创建上传的点击按钮
      var interval = $('<div></div>').addClass('interval');
      container.append(interval);
      var uploadBtn = $('<image src="../dist/image/fq-128.png"></image>').addClass('button');
      container.append(uploadBtn);
      //4、创建隐藏的文本保存区
      var file = $('<input />').attr('type', 'file').attr('name', 'file').addClass('file')
                                .attr('id','file');
      container.append(file);
      //5、创建图片回显区
      var imgContainer = $('<div></div>').addClass('show');
      // var img = $('<img src="../dist/image/plus_sign.png">').attr('id', 'myimg');
      // imgContainer.append(img);
      container.append(imgContainer);
    }
  }
  
  window.addEventListener("DOMContentLoaded", function () {
    $('.button').click(function(e) {
      $('#file').click();
    });
    $('#file').change(function(e) {
      console.log('新上传图片');
      if (document.getElementById('file').value != '') {
        createImgShow();
      }
    })
    function createImgShow() {
      var url = getFileUrl();
      var img = $('<img src="'+url+'">')
      $('.show').prepend(img);
      // console.log('界面加载完毕');
      //将图片上传至服务器
      ajaxFileUpload('show');
    }

    //获取input[file]图片的url Important
    function getFileUrl() {
      var url;
      var file = document.getElementById('file');
      var agent = navigator.userAgent;
      
      if (agent.indexOf("MSIE")>=1) {
        url = file.value;
      } else if(agent.indexOf("Firefox")>0) {
        url = window.URL.createObjectURL(file.files.item(0));
      } else if(agent.indexOf("Chrome")>0) {
        url = window.URL.createObjectURL(file.files.item(0));
      }else {
        console.log('未识别游览器类型：'+agent);
        // console.log(file.files.item(0));
        url = window.URL.createObjectURL(file.files.item(0));
      }
      return url;
    }

    function ajaxFileUpload(from_id) {
      //上传图片 min_flag=0 原图不生成缩略图 min_flag = 1 生成缩略图 min_flag=2 批量上传 call_back 返回结果处理
      var min_flag = 1;
      var call_back = null;
      var com = {};
      com.imgWidth = 100;
      com.imgHeight = 100;
      com.imgurl = 'http://172.16.2.221'; //上传服务器ID
      console.log(from_id);
      com.ajaxFileUpload = ajaxFileUpload(com, from_id, min_flag, call_back);
    }

    function ajaxFileUpload(com, from_id, min_flag, call_back) {
      console.log('开始上传图片');
      // console.log($('.' + from_id + ' img').val);
      if ($('.' + from_id + ' img')) {
          var formData = new FormData();
          // var loading = layer.load();
          var ajax_url = com.imgurl + '/upload/upload';
          if (min_flag == 0) { //单张上传无缩略图
              formData = new FormData($("." + from_id)[0]);
          } else if (min_flag == 1) { //单张上传有缩略图
              ajax_url = com.imgurl + '/upload/uploadcompress/' + com.imgWidth + '/' + com.imgHeight;
              formData = new FormData($("." + from_id)[0]);
              console.log(formData);
          } else if (min_flag == 2) { //批量上传
              var dom_IdTemp = $('#' + from_id).find("input").attr("id");
              ajax_url = com.imgurl + '/upload/uploadmulticompress/0/0';
              var themFlag = $('#' + dom_IdTemp).data('thempflag'); //批量上传的时候 themFlag 等于1 生成缩略图  等于0不生成缩略图
              if (themFlag == 1) {
                  ajax_url = com.imgurl + '/upload/uploadmulticompress/' + com.imgWidth + '/' + com.imgHeight;
              }
              var files = document.getElementById(dom_IdTemp).files;
              var nameTemp = $('#' + dom_IdTemp).attr("name");
              for (var i = 0; i < files.length; i++) {
                  formData.append(nameTemp + "[" + i + "]", files[i]);
              }
          } else if(min_flag == 3){//视频上传 返回封面图
              ajax_url=com.imgurl+'/upload/uploadmulticompress/subVideo';
              formData = new FormData($("." + from_id)[0]);
          }else {
              formData = new FormData($("." + from_id)[0]);
          }

          $.ajax({
              url: ajax_url,
              type: 'POST',
              data: formData,
              async: false,
              cache: false,
              dataType: 'json',
              crossDomain: true,
              headers: {
              // 'Authorization': com.getcookie('aTokenV1')
              },
              jsonp: "callback",
              contentType: false,
              processData: false,
              success: function(returndata) {
                  // layer.close(loading);
                  call_back(returndata);
                  // $('#' + from_id + ' img').val(''); //返回数据之后清理input数据
              },
              error: function(returndata) {
                  //layer.msg(returndata.msg);
                  // layer.close(loading);
              }
          });
      }else {
        console.log('没有可上传的图片资源');
      }
    }



  }, false);

  if (!win.dyPlugins) {
    win.dyPlugins = {};
  }
  dyPlugins.Upload = upload;
}(window);
